package com.mulitidatasource.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource("classpath:db1.properties")
@MapperScan(basePackages= {"testdb.mulitidatasource.mapper.db1"},sqlSessionTemplateRef="db1SqlSessionTemplate")
public class Db1Config {
	//@Primary
	@Bean(name="db1DataSource")
	public DataSource db1DataSource(@Value("${spring.datasource.db1.driver-class-name}")String driverClassName,
			@Value("${spring.datasource.db1.jdbc-url}")String url,
			@Value("${spring.datasource.db1.userName}")String username,
			@Value("${spring.datasource.db1.password}")String password){
		DataSource dataSource = DataSourceBuilder.create().url(url).driverClassName(driverClassName).password(password).username(username).build();
		return dataSource;
	}
	
	//@Primary
	@Bean(name="db1SqlSessionFactory")
	public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource")DataSource dataSource) throws Exception{
		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
		sqlSessionFactoryBean.setDataSource(dataSource);
        // mapper的xml形式文件位置必须要配置，不然将报错：no statement （这种错误也可能是mapper的xml中，namespace与项目的路径不一致导致）
        //bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/db1/*.xml"));
		return sqlSessionFactoryBean.getObject();
	}
	
	//@Primary
	@Bean(name="db1SqlSessionTemplate")
	public SqlSessionTemplate db1SqlSessionTemplate(@Qualifier("db1SqlSessionFactory")SqlSessionFactory sqlSessionFactory){
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}
